package handlers

import (
	"building-mgr/cache"
	"building-mgr/models"
	"building-mgr/pkg"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "用户不存在",
		})
		return
	}
	fmt.Println("用户不存在")
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	var life = models.Life{
		Title:   title,
		Content: content,
		Img:     img,
	}
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	err := models.DB.Create(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	reids_key := "cache_data_" + life.Title
	var data models.Life
	models.DB.Where("id = ?", life.ID).First(&data)
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, reids_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func List(c *gin.Context) {
	var life models.Life
	id := c.Query("id")
	err := models.DB.Where("id=?", id).First(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"life": life,
		"msg":  "查询成功",
	})
}

func Delete(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id = ?", id).Delete(&models.Life{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "cache_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func Lists(c *gin.Context) {
	var life []models.Life
	err := models.DB.Find(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "cache_id_" + life[0].Title
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&life)
		jsonData, _ := json.Marshal(life)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &life)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": life,
		"msg":  "成功",
	})
	return
}
